package cn.edu.service;

import cn.edu.entity.MyUser;
import cn.edu.entity.Permission;
import cn.edu.mapper.PermissionMapper;
import cn.edu.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Mr.ma
 * @since 2023/1/3 20:35
 **/
@Service
public class UserService implements UserDetailsService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<MyUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        MyUser myUser = userMapper.selectOne(queryWrapper);
        if (myUser != null){
            List<Permission> permissions = permissionMapper.selectPerByUid(myUser.getUserid());
            Collection<? extends GrantedAuthority> collect = permissions
                    .stream()
                    .map(x -> new SimpleGrantedAuthority(x.getPercode()))
                    .collect(Collectors.toList());

            User user = new User(username, myUser.getUserpwd(), collect);
            return user;
        }
        return null;
    }
}
